from typing import Optional

from fastapi import APIRouter, Depends
from starlette.requests import Request
from tortoise import Model

from fastadmin.depends import get_model, get_model_resource, get_resources
from fastadmin.resources import Model as ModelResource
from fastadmin.template import render_values, templates

router = APIRouter()


@router.get("/list/{resource}")
async def list_view(
    request: Request,
    model: Model = Depends(get_model),
    resources=Depends(get_resources),
    resource: ModelResource = Depends(get_model_resource),
    size: Optional[int] = None,
):
    fields_name = resource.get_fields_name()
    fields_label = resource.get_fields_label()
    fields = resource.get_fields()
    values = await model.all().values_list(*fields_name)
    values = await render_values(fields, values)
    filters = await resource.get_filters()
    return templates.TemplateResponse(
        "list.html",
        context={
            "request": request,
            "resources": resources,
            "fields_label": fields_label,
            "fields": fields,
            "values": values,
            "filters": filters,
            "resource_label": resource.label,
            "page_size": size or resource.page_size,
            "page_title": resource.page_title,
            "page_pre_title": resource.page_pre_title,
        },
    )


@router.get("/edit/{resource}")
async def edit_view(request: Request, resource: str, resources=Depends(get_resources)):
    return templates.TemplateResponse(
        "edit.html", context={"request": request, "resources": resources}
    )
